<template>
  <el-container class="main_con">
    <div class="edit_con">
      <div class="edit_title">{{ pageName }}</div>
      <div class="edit_content">
        <el-form label-width="100px" ref="shForm" :model="obj" :rules="itemRules" class="edit_form">
          <el-form-item label="用户账号" prop="user_name">
            <span style="margin-right: 5px;">{{ obj.user_name }}</span>
            <el-button type="text" @click="showUser = true">选择</el-button>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile"><el-input size="medium" placeholder="请输入手机号" v-model="obj.mobile"></el-input></el-form-item>

          <el-form-item label="商户名" prop="name"><el-input size="medium" placeholder="请输入商户名" v-model="obj.name"></el-input></el-form-item>
          <el-form-item label="商户logo" prop="business_license">
            <div class="img_box"><Upload :tempUrl="obj.logo" @input="getImage_logo"></Upload></div>
          </el-form-item>

          <el-form-item label="公司" prop="company"><el-input size="medium" placeholder="请输入公司名称" v-model="obj.company"></el-input></el-form-item>

          <!-- <el-form-item label="所在区域" prop="districtSelected">
            <el-cascader
              size="medium"
              :options="options"
              v-model="obj.districtSelected"
              @change="districtSelect"
              @visible-change="validateDistrict"
              ref="location"
              style="width:100%">
            </el-cascader>
          </el-form-item>-->

          <el-form-item label="所在区域" prop="districtSelected">
            <el-cascader size="medium" :options="options" v-model="obj.districtSelected" @change="districtSelect" ref="location" style="width:100%"></el-cascader>
          </el-form-item>

          <el-form-item label="地址" prop="address"><el-input size="medium" placeholder="请输入具体地址" v-model="obj.address"></el-input></el-form-item>

          <el-form-item label="商户位置" prop="longitude">
            <div style="display:flex">
              <div>
                <el-col :span="12"><el-input size="medium" placeholder="请输入经度" v-model="obj.longitude"></el-input></el-col>
                <el-col :span="1" class="t_c">-</el-col>
                <el-col :span="11"><el-input size="medium" placeholder="请输入纬度" v-model="obj.latitude"></el-input></el-col>
              </div>
              <el-button size="medium" class="ml_15" @click="showMap = true">获取坐标</el-button>
            </div>
          </el-form-item>

          <el-form-item label="备注"><el-input size="medium" placeholder="请输入备注内容" v-model="obj.remark"></el-input></el-form-item>

          <el-form-item label="详细介绍"><el-input size="medium" type="textarea" rows="4" placeholder="请输入商户详细介绍内容" v-model="obj.content"></el-input></el-form-item>

          <el-form-item label="营业执照" prop="business_license">
            <div class="img_box"><Upload :tempUrl="obj.business_license" @input="getImage"></Upload></div>
          </el-form-item>

          <el-form-item label="有效期" prop="indate">
            <el-col :span="14">
              <el-date-picker
                size="medium"
                v-model="obj.indate"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
                :disabled="indate"
                type="datetime"
                placeholder="选择有效期"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
            <el-col class="line t_c" :span="5">永久有效</el-col>
            <el-col :span="5"><el-switch v-model="indate" @change="changeInDate"></el-switch></el-col>
          </el-form-item>

          <el-form-item label="免审核">
            <el-radio-group v-model="obj.audit_type">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="obj.status">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">正常</el-radio>
              <!-- <el-radio :label="2">禁用</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="edit_footer"><el-button size="medium" type="primary" @click="saveData">保存数据</el-button></div>
    </div>

    <el-dialog title="选取坐标" :visible.sync="showMap" custom-class="maps" width="70%"><AMap @submitClose="closeMap" :pos="[120.683311, 28.007002]"></AMap></el-dialog>
    <el-dialog :visible.sync="showpassword" width="600px">
      <div class="ps_div">
        <span>商户新增成功！复制初始账号发给商户。</span>
        <el-form>
          <el-form-item label="初始账号">
            <span>{{ secret.username }}</span>
          </el-form-item>
          <el-form-item label="初始密码">
            <span>{{ secret.password }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="showpassword = false">取 消</el-button>
        <el-button type="primary" @click="doCopy">复制</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择用户" :visible.sync="showUser" width="60%"><SelectUser @outData="getuser" :hidden="true" :data="userlist" :limit="1"></SelectUser></el-dialog>
  </el-container>
</template>

<script>
import DatePicker from '@/components/DatePicker/index';
import Upload from '@/components/Upload/SingleImage2';
import AMap from '@/components/AMap/index';
import SelectUser from '@/components/SelectUser/index';
import {regionData, CodeToText, TextToCode} from 'element-china-area-data';
import {getMerchantList, addMerchant, editMerchant, getMerchant, getUserList, getMerchantApply} from '@/api/mall/merchant';
export default {
  data() {
    //校验手机号码
    let validateMobile = (rule, value, callback) => {
      if (!/^1[23456789]\d{9}$/.test(value)) {
        callback(new Error('手机号码有误，请重填'));
      } else {
        callback();
      }
    };
    //校验区域
    // let validateDistrict = (rule, value,callback) => {
    //   if(value.length == 0){
    //     callback(new Error('请选择区域'));
    //   }
    // };

    //校验经纬度
    let validateLocation = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('经纬度不能为空'));
      } else if (this.obj.latitude == '') {
        callback(new Error('经纬度不能为空'));
      } else {
        callback();
      }
    };

    //校验有效期
    let validateInDate = (rule, value, callback) => {
      if (!this.indate) {
        //没选中永久有效
        if (value == '') {
          callback(new Error('有效期不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      showMap: false,
      showpassword: false,
      showUser: false,
      secret: {},
      userlist: [],
      obj: {
        user_id: '',
        user_name: '', //校验用用户名字段
        name: '',
        mobile: '',
        company: '',
        logo: '',
        district: '',
        districtSelected: [],
        address: '',
        longitude: '',
        latitude: '',
        business_license: '',
        type: 1, //0:单门店,1:多门店
        indate: '',
        remark: '',
        content: '',
        audit_type: 0, //是否免审核:0:不免(默认),1:免审核
        status: 1 //0:未启用;1:正常;2:禁用
        //apply_id:'',//申请id,通过申请时使用
        //update_time:''//更新时间,通过申请时使用
      },
      _obj: {},
      pageIsEdit: 0, //0->新增,1->编辑,2->通过申请
      pageName: '新增商户',
      indate: false,
      isLoading: false,
      options: regionData,
      itemRules: {
        user_name: [
          {
            required: true,
            trigger: 'blur',
            message: '请先选择用户'
          }
        ],
        mobile: [
          {
            required: true,
            trigger: 'blur',
            validator: validateMobile
          }
        ],
        name: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商户名'
          }
        ],
        company: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入公司'
          }
        ],
        longitude: [
          {
            required: true,
            //trigger: 'blur',
            validator: validateLocation
          }
        ],
        address: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入具体地址'
          }
        ],
        districtSelected: [
          {
            type: 'array',
            required: true,
            //trigger: 'change',
            message: '请选择所在区域'
          }
        ],
        business_license: [
          {
            required: true,
            trigger: 'change',
            message: '营业执照不能为空'
          }
        ],
        indate: [
          {
            required: true,
            trigger: 'blur',
            validator: validateInDate
          }
        ]
      },
      showpassword: false,
      secret: {}
    };
  },
  components: {
    DatePicker,
    Upload,
    AMap,
    SelectUser
  },
  created() {
    //获取路由参数(编辑时使用)
    if (this.$route.query.id) {
      //编辑页面
      this.pageIsEdit = 1;
      this.pageName = '编辑商户';
      this.getMerchantData(this.$route.query.id);
    } else if (this.$route.query.aid) {
      //通过申请记录
      this.pageIsEdit = 2;
      this.pageName = '通过申请';
      this.getMerchantApply(this.$route.query.aid);
    } else {
      this.pageIsEdit = 0;
      this.pageName = '新增商户';
      this._obj = Object.assign({}, this.obj);
    }
  },
  methods: {
    getuser(data) {
      
      if (data && data.length > 0) {
        this.obj.user_id = data[0].id;
        this.obj.user_name = data[0].nickname;
      }
      this.showUser = false;
    },
    //复制单号
    doCopy() {
      let data = '商户' + this.obj.name + '新增成功,' + '初始登录账号：' + this.secret.username + ',初始登录密码：' + this.secret.password;
      this.$copyText(data).then(
        res => {
          //this.$alert('复制成功');
          this.$message({
            message: '复制成功',
            type: 'success',
            duration: 2000
          });
        },
        error => {
          this.$alert('无法复制');
        }
      );
    },
    //搜索用户，获取用户ID
    queryUserId(s, cb) {
      // let rs = this.rs;
      // let results = s ? rs.filter(this.createFilter(s)) : rs;
      // cb(results);
      if (s !== '') {
        let data = {
          nickname: s
        };

        getUserList(data).then(res => {
          let o = res.msg;
          let list = o.data;
          if (list.length == 0) {
            this.$message({
              message: '未找到匹配的用户',
              type: 'warning',
              duration: 2 * 1000
            });
          } else {
            list.forEach(a => {
              if (!a.name) {
                a.name = a.nickname;
              }
            });
          }

          cb(list);
        });
      } else {
        cb([]);
      }
    },
    //点击图标
    // iconClick(ev){
    //   console.log(ev);
    // },
    //获取编辑页面基础数据
    getMerchantData(id) {
      this.isLoading = true;
      getMerchant(id).then(res => {
        this.isLoading = false;
        let o = res.msg;
        //this.obj = o;

        //处理所在区域
        let _d = [];
        let _t;
        if (o.district.indexOf(',') > -1) {
          _t = o.district.split(',');
        } else {
          _t = o.district.split(' ');
        }
        //拼接所在区域选择数组
        _d[0] = TextToCode[_t[0]].code;
        _d[1] = TextToCode[_t[0]][_t[1]].code;
        _d[2] = TextToCode[_t[0]][_t[1]][_t[2]].code;
        o.districtSelected = _d;

        //处理商户状态
        switch (o.status) {
          case '未启用':
            o.status = 0;
            break;
          case '正常':
            o.status = 1;
            break;
          case '禁用':
            o.status = 2;
            break;
          default:
            //no code
            break;
        }

        //处理是否永久有效
        if (o.indate == 0) {
          this.indate = true;
        } else {
          this.indate = false;
        }
        this.userlist.push({
          id: o.user_id
        });
        //赋值
        this.obj = Object.assign({}, o);
      });
    },
    //获取通过申请页面基础数据
    getMerchantApply(id) {
      this.isLoading = true;
      getMerchantApply(id).then(res => {
        this.isLoading = false;
        let o = res.msg;

        //处理数据,status字段不处理
        // //处理所在区域
        // let _d = [];
        // let _t;
        // if(o.district.indexOf(',') > -1){
        //   _t = o.district.split(',');
        // }else{
        //   _t = o.district.split(' ');
        // };
        //拼接所在区域选择数组
        // _d[0] = TextToCode[_t[0]].code;
        // _d[1] = TextToCode[_t[0]][_t[1]].code;
        // _d[2] = TextToCode[_t[0]][_t[1]][_t[2]].code;
        // o.districtSelected = _d;

        //补全整理字段
        delete o.id;
        // o.business_license = "";
        o.tpye = 1;
        o.indate = '';
        o.status = 0;
        o.apply_id = id;
        this.userlist.push({
          id: o.user_id
        });
        //赋值
        this.obj = Object.assign({}, o);
      });
    },
    //选择用户
    selectUserId(item) {
      this.obj.user_name = item.nickname;
      this.obj.user_id = item.id;
      //this.obj.mobile = item.mobile;

      //this.$refs.shForm.validateField('mobile');
    },
    //选择是否永久有效
    changeInDate(flag) {
      //console.log(val)
      if (flag) {
        //永久有效
        this.obj.indate = '';
      } else {
        //no code
      }
      this.$refs.shForm.validateField('indate');
    },
    //获取图片
    getImage(val) {
      this.obj.business_license = val;
    },
    getImage_logo(val) {
      this.obj.logo = val;
    },
    //级联选择区域
    districtSelect(value) {
      let s = '';
      if (!Array.isArray(value)) {
        return false;
      }
      value.forEach(e => {
        s += CodeToText[e] + ',';
      });
      s = s.substring(0, s.length - 1);
      //对象赋值
      this.obj.district = s;
    },
    //手动侦听事件触发校验
    validateDistrict(e) {
      //console.log(this.$refs.shForm)
      //this.$refs.shForm.validateField('districtSelected');
    },
    //保存数据
    saveData() {
      let that = this;
      let _data = Object.assign({}, this.obj);
      this.$refs.shForm.validate(valid => {
        if (valid) {
          //处理数据
          if (that.indate) {
            _data.indate = '0';
          }

          //delete _data.apply_id;
          //delete _data.update_time;

          //删除所在无用字段
          delete _data.districtSelected;
          //delete _data.user_name;

          //保存数据
          this.isLoading = true;
          switch (this.pageIsEdit) {
            case 2:
            //通过申请
            //console.log(_data);

            case 0:
              //新增
              addMerchant(_data)
                .then(res => {
                  this.isLoading = false;
                  // this.showpassword = true;
                  // console.log(res);
                  // this.secret = res.msg.secret;
                  this.$refs.shForm.resetFields();
                  this.obj = Object.assign({}, this._obj);
                  this.$router.push('/merchant/list');
                })
                .catch(e => {
                  this.isLoading = false;
                });
              break;
            case 1:
              //编辑
              delete _data.status_text;
              //_data.test = 1;
              editMerchant(_data)
                .then(res => {
                  this.isLoading = false;
                  //this.getMerchantData(this.$route.query.id);
                  this.$router.push('/merchant/list');
                })
                .catch(e => {
                  this.isLoading = false;
                });
              break;
            default:
              //no code
              break;
          }
        } else {
          //console.log('error')
          return false;
        }
      });
    },
    //关闭坐标选择器窗口
    closeMap(e) {
      this.showMap = false;
      this.obj.longitude = e[0];
      this.obj.latitude = e[1];
    }
  }
};
</script>

<style lang="scss">
.ps_div {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
.img_box {
  width: 200px;
  height: 200px;
}
</style>
